// START WRAPPER: The YUI.add wrapper is added by the build system, when you use YUI Builder to build your component from the raw source in this file
 YUI.add("logindetector", function(Y) {

    /* Any frequently used shortcuts, strings and constants */
    var Lang = Y.Lang;

    /* LoginDetector class constructor */
    function LoginDetector(config) {
        LoginDetector.superclass.constructor.apply(this, arguments);
    }

    /* 
     * Required NAME static field, to identify the class and 
     * used as an event prefix, to generate class names etc. (set to the 
     * class name in camel case). 
     */
    LoginDetector.NAME = "loginDetector";

    /*
     * The attribute configuration for the component. This defines the core user facing state of the component
     */
    LoginDetector.ATTRS = {
    	showMsg : {
    		value : true
    	},
        attrA : {
            value: "A"                     // The default value for attrA, used if the user does not set a value during construction.

            /*
            , valueFn: "_defAttrAVal"      // Can be used as a substitute for "value", when you need access to "this" to set the default value.
             
            , setter: "_setAttrA"          // Used to normalize attrA's value while during set. Refers to a prototype method, to make customization easier
            , getter: "_getAttrA"          // Used to normalize attrA's value while during get. Refers to a prototype method, to make customization easier
            , validator: "_validateAttrA"  // Used to validate attrA's value before updating it. Refers to a prototype method, to make customization easier

            , readOnly: true               // Cannot be set by the end user. Can be set by the component developer at any time, using _set
            , writeOnce: true              // Can only be set once by the end user (usually during construction). Can be set by the component developer at any time, using _set
            
            , lazyAdd: false               // Add (configure) the attribute during initialization. 
            
                                           // You only need to set lazyAdd to false if your attribute is
                                           // setting some other state in your setter which needs to be set during initialization 
                                           // (not generally recommended - the setter should be used for normalization. 
                                           // You should use listeners to update alternate state). 

            , broadcast: 1                 // Whether the attribute change event should be broadcast or not.
            */
        }

        // ... attrB, attrC, attrD ... attribute configurations. 

        // Can also include attributes for the super class if you want to override or add configuration parameters
    };

    /* LoginDetector extends the Base class */
    Y.extend(LoginDetector, Y.Base, {

        initializer: function() {
            /*
             * initializer is part of the lifecycle introduced by 
             * the Base class. It is invoked during construction,
             * and can be used to setup instance specific state or publish events which
             * require special configuration (if they don't need custom configuration, 
             * events are published lazily only if there are subscribers).
             *
             * It does not need to invoke the superclass initializer. 
             * init() will call initializer() for all classes in the hierarchy.
             */
        	this.increament = 0;
             this.publish("loginDetectReady", {
                defaultFn: this._defMyEventFn,
                bubbles:false
             });
        },

        destructor : function() {
            /*
             * destructor is part of the lifecycle introduced by 
             * the Base class. It is invoked when destroy() is called,
             * and can be used to cleanup instance specific state.
             *
             * It does not need to invoke the superclass destructor. 
             * destroy() will call initializer() for all classes in the hierarchy.
             */
        },

        /* LoginDetector specific methods */
        
        _transStart: function(id, args) {
        	if(this.get('showMsg'))Y.showMsg('检测用户登录状态...');
           },
           
         _transComplete: function(id, o, args) {
	    	if(this.get('showMsg'))Y.hideMsg();
	    },
	    _transSuccess: function(id, o, args) {
	    		var showMsg = this.get('showMsg');
	    			if(showMsg)Y.hideMsg();
	    			var r = Y.JSON.parse(o.responseText);
	    			var al = o.getResponseHeader('Accept-Language'); 
	    			Y.log(al);
	    			this._translateApp(al);
	    			var res = r.response;
	    			if(res.status === 0){
	    				this._uuid = res.m3958extra.uuid;
	    				if(res.data.length === 1){
	    					var u = res.data[0];
	    					Y.loginUser = u;
	    					this.loginUser = u;
	        				Y.fire('loginStatus',{login:true,user:u});
	        				this.fire('loginDetectReady',{login:true,user:u});
	        				if(showMsg)Y.hideWarn();
	    				}else{
	        				Y.fire('loginStatus',{login:false});
	        				this.fire('loginDetectReady',{login:false});
	    				}
	    			}else{
	    				if(showMsg)Y.showWarn("登录状态监测出错，请尝试刷新浏览器！");
	    			}
	             },
         _transFailure: function(id, o, args) {
        	 if(this.get('showMsg')){
	    			Y.hideMsg();
	    			Y.showWarn("与服务器的通讯故障，请稍候再试！");
        	 }
	             },
         _transEnd: function(id, args) {
	    		if(this.get('showMsg'))Y.hideMsg();
	    },
	             
		_translateApp : function(al){
			var lang = Y.Cookie.get('uxu123-lang');
			if(lang){
				if(Y.Intl.getLang() == lang){
					;
				}else{
					Y.translateApp(lang);
				}
			}else{
				//en-us,zh-cn;q=0.7,zh;q=0.3
				var langs = al.split(',');
				if(langs.length > 0){
					var l = langs[0].split(';')[0].split('-')[0];
					Y.log(l);
					var availLangs = Y.Intl.getAvailableLangs("translator");
					Y.log(availLangs);
					Y.some(availLangs,function(item){
						if(item.indexOf(l) == 0){
							Y.translateApp(item);
							return true;
						}
					});
					
				}else{
					;//没有足够的信息，就默认了。
				}
			}
		},       
	             
	    startDetect : function(){
	    	var outThis = this;
            var cfg = {
                    on: {
                        start: outThis._transStart,
                        complete: outThis._transComplete,
                        success: outThis._transSuccess,
                        failure: outThis._transFailure,
                        end: outThis._transEnd
                    },
                    data:"_loginstatusdetect=true",
                    context: this,
                    arguments: {}
                };
           	Y.io('/notrpclogin', cfg);
	    },
	    
	    getNextUUID : function(){
	    	if(this._uuid){
	    		return this._uuid + this.increament++;
	    	}else{
	    		return this.increament++;
	    	}
	    },
        _defMyEventFn : function(e) {
            // The default behavior for the "myEvent" event.
        }
    });

    Y.namespace("M3958").LoginDetector = LoginDetector;

 },'0.0.1',{requires:['base','io-base', 'node','json-parse','cookie']});
 
// END WRAPPER


//YUI.add('logindetector', function (Y) {
//	var indicator = Y.one('#indicator-img');
//	
//	function translateApp(al){
//		var lang = Y.Cookie.get('uxu123-lang');
//		if(lang){
//			if(Y.Intl.getLang() == lang){
//				;
//			}else{
//				Y.translateApp(lang);
//			}
//		}else{
//			//en-us,zh-cn;q=0.7,zh;q=0.3
//			var langs = al.split(',');
//			if(langs.length > 0){
//				var l = langs[0].split(';')[0].split('-')[0];
//				Y.log(l);
//				var availLangs = Y.Intl.getAvailableLangs("translator");
//				Y.log(availLangs);
//				Y.some(availLangs,function(item){
//					if(item.indexOf(l) == 0){
//						Y.translateApp(item);
//						return true;
//					}
//				});
//				
//			}else{
//				;//没有足够的信息，就默认了。
//			}
//		}
//	}
	
//    var gH = {
//            start: function(id) {
//            	indicator.show();
//            },
//            complete: function(id, o) {
//            	indicator.hide();
//            },
//            success: function(id, o) {
//            	indicator.hide();
//            },
//            failure: function(id, o) {
//            	indicator.hide();
//            },
//            end: function(id) {
//            	indicator.hide();
//            }
//        };
//    
//		var tH = {
//            start: function(id, args) {
//            		indicator.show();
//                	Y.showMsg('检测用户登录状态...');
//                   },
//            complete: function(id, o, args) {
//            	Y.hideMsg();
//            	indicator.hide();
//            },
//            success: function(id, o, args) {
//            			indicator.hide();
//            			Y.hideMsg();
//            			var r = Y.JSON.parse(o.responseText);
//            			var al = o.getResponseHeader('Accept-Language'); 
//            			Y.log(al);
//            			translateApp(al);
//            			var res = r.response;
//            			if(res.status === 0){
//            				if(res.data.length === 1){
//            					var u = res.data[0];
//            					Y.loginUser = u;
//                				Y.fire('loginStatus',{login:true,user:u});
//                				Y.hideWarn();
//            				}else{
//                				Y.fire('loginStatus',{login:false});
//            				}
//            			}else{
//            				Y.showWarn("登录状态监测出错，请尝试刷新浏览器！");
//            			}
//                     },
//            failure: function(id, o, args) {
//            			indicator.hide();
//            			Y.hideMsg();
//            			Y.showWarn("与服务器的通讯故障，请稍候再试！");
//                     },
//            end: function(id, args) {
//            		Y.hideMsg();
//            		indicator.hide();
//            }
//        };
//        
//        /* configuration object for transactions */
//        var cfg = {
//            on: {
//                start: tH.start,
//                complete: tH.complete,
//                success: tH.success,
//                failure: tH.failure,
//                end: tH.end
//            },
//            data:"_loginstatusdetect=true",
//            context: tH,
//            arguments: {}
//        };
//        
//        /* attach global listeners */
//        Y.on('io:start', gH.start, gH);
//        Y.on('io:complete', gH.complete, gH);
//        Y.on('io:success', gH.success, gH);
//        Y.on('io:failure', gH.failure, gH);
//        Y.on('io:end', gH.end, gH);
//        /* end global listener binding */
//        Y.loginDetect = function(){
//        	Y.io('/notrpclogin', cfg);
//        };
//},'0.0.1',{requires:['io-base', 'node','json-parse']});
 
 